package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.DrivingService;
import com.gljx.web.service.TrainingChargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class TrainingChargeController {

	//自动注入
	@Autowired
	private TrainingChargeService trainingChargeService;
	
	//自动注入
	@Autowired
	private DrivingService drivingService;
	
	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;
	/**
	 * 查询自带车训练收费
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryTrainingCharge/look.action")
	public String queryTrainingCharge(HttpServletRequest request){
		PageBean<TrainingCharge> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<TrainingCharge> trainingCharges = pb.getBeanList();
			for (TrainingCharge trainingCharge : trainingCharges) {
				//根据父类id查询子类信息
				List<TrainingChargeEntry> trainingChargeEntrys = trainingChargeService.quertTrainingChargeEntryByInfo(trainingCharge.getFid(), "", "");
				//把子类信息放进来
				trainingCharge.setTrainingChargeEntrys(trainingChargeEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("pb", pb);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("trainingCharges", trainingCharges);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "/backHome/financialManagement/trainingCharge/trainingChargeList";
	}
	
	/**
	 * 根据条件查询
	 * @param request
	 * @param cfcar 车牌
	 * @param drivingName 驾校名称
	 * @param beginTime 业务开始时间
	 * @param endTime 业务结束时间
	 * @return
	 */
	@RequestMapping("/queryTrainingChargeByInfo")
	public String queryTrainingChargeByInfo(HttpServletRequest request,String cfcar,String drivingName,String beginTime,String endTime){
		PageBean<TrainingCharge> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//获取分页
			pb = getPageBean2(request,user.getFcompanyid(),cfcar,drivingName,beginTime,endTime);
			//获取分页数据
			List<TrainingCharge> trainingCharges = pb.getBeanList();
			for (TrainingCharge trainingCharge : trainingCharges) {
				//根据父类id查询子类信息
				List<TrainingChargeEntry> trainingChargeEntrys = trainingChargeService.
						quertTrainingChargeEntryByInfo(trainingCharge.getFid(), drivingName, cfcar);
				//把子类信息放进来
				trainingCharge.setTrainingChargeEntrys(trainingChargeEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("pb", pb);
			request.setAttribute("trainingCharges", trainingCharges);
			request.setAttribute("cfcar", cfcar);
			request.setAttribute("drivingName", drivingName);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/financialManagement/trainingCharge/trainingChargeList";
	}

	@ResponseBody
	@RequestMapping(value = "/selTrainingChargeByCar")
	public TrainingChargeEntry selTrainingChargeByCar(HttpServletRequest request,String car) {
		TrainingChargeEntry trainingChargeEntry = new TrainingChargeEntry();
        					trainingChargeEntry = trainingChargeService.selTrainingChargeByCar(car, GetUserSession.getUserSession(request));
        return trainingChargeEntry;
    }

	/**
	 * 跳转到添加页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertTrainingCharge")
	public String insertTrainingCharge(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询所有协议驾校
		List<Driving> drivings = drivingService.queryDrivingAll(user.getFcompanyid());
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("CT_DS_TRAININGCHARGE",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("ZD");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//开始时间
		String time = sdf.format(new Date());
		//把数据传到页面
		request.setAttribute("time", time);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("drivings", drivings);
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		return "/backHome/financialManagement/trainingCharge/editTrainingCharge";
	}
	
	/**
	 * 根据名称查询驾校
	 * @param name
	 * @return
	 */
	@RequestMapping("/queryDrivingByName")
	@ResponseBody
	public List<Driving> queryDrivingByName(String name, HttpServletRequest request) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Driving> drivings = new ArrayList<>();
		if(name == null || "".equals(name)){
			drivings = drivingService.queryDrivingAll(user.getFcompanyid());
		}else{
			drivings = drivingService.queryDrivingByFnameL2(name, user.getFcompanyid());
		}
		return drivings;
	}
	
	/**
	 * 添加,修改自带车训练收费
	 * @param request
	 * @param trainingCharge 属性自动封装
	 * @return
	 */
	@RequestMapping("/editTrainingCharge")
	public String editTrainingCharge(HttpServletRequest request,TrainingCharge trainingCharge,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		trainingCharge.setFcontrolunitid(user.getFcompanyid());
		//公司id
		trainingCharge.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		trainingCharge.setFhandlerid(user.getFid());
		/**获取子类信息集合**/
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//车牌
		String[] cfcar = request.getParameterValues("cfcar");
		//车型
		String[] cfcartype = request.getParameterValues("cfcartype");
		//协议驾校id
		String[] cfjiaxiaoid = request.getParameterValues("cfjiaxiaoid");
		//时长
		String[] cftime = request.getParameterValues("cftime");
		//返点
		String[] cffandian = request.getParameterValues("cffandian");
		//总时长
		String[] cfzsc = request.getParameterValues("cfzsc");
		//单价
		String[] cfprice = request.getParameterValues("cfprice");
		//金额
		String[] cfamount = request.getParameterValues("cfamount");
		//人数
		String[] cfnumber = request.getParameterValues("cfnumber");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//添加或修改
		trainingChargeService.editTrainingCharge(trainingCharge,fseq,cfcar,cfcartype,cfjiaxiaoid,cftime,cffandian,cfzsc,cfprice,
				cfamount,cfnumber,cfremark,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
			customLogService.addLog("财务管理", time+"对自带车训练收费进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertTrainingCharge?type=3";
		}else{
			//添加日志
			customLogService.addLog("财务管理", time+"对自带车训练收费进行修改操作", null, user.getFid());
			//重定向到查询页面
            queryTrainingChargeByFid(request,fid);
            request.setAttribute("type",3);
            return "/backHome/financialManagement/trainingCharge/editTrainingCharge";
		}
		
	}
	
	/**
	 * 根据fid删除
	 * @param deleteId 多个
	 * @param fid 单个
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteTrainingChargeByFid")
	public String deleteTrainingChargeByFid(String[] deleteId,String fid,HttpServletRequest request){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
		trainingChargeService.deleteTrainingChargeByFid(deleteId,fid);
		//添加日志
		customLogService.addLog("财务管理", TimeFormat.timeFormat(new Date())+"对自带车训练收费进行删除操作", null, user.getFid());
		//重定向到查询页面
		return "redirect:/DrivingSys/queryTrainingCharge/look.action";
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryTrainingChargeByFid")
	public String queryTrainingChargeByFid(HttpServletRequest request,String fid){
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//查询所有协议驾校
		List<Driving> drivings = drivingService.queryDrivingAll(user.getFcompanyid());
		//根据fid查询
		TrainingCharge trainingCharge = trainingChargeService.queryTrainingByFid(fid);
		//查询子类
		List<TrainingChargeEntry> trainingChargeEntrys = trainingChargeService.quertTrainingChargeEntryByInfo(fid, "", "");
		//把数据传到页面
		request.setAttribute("drivings", drivings);
		request.setAttribute("trainingChargeEntrys", trainingChargeEntrys);
		request.setAttribute("trainingCharge", trainingCharge);
		return "/backHome/financialManagement/trainingCharge/editTrainingCharge";
	}
	
	/**
	 * 审核。反审核
	 * @param request
	 * @param fid
	 * @param type 1：审核    2：反审核
	 * @return
	 */
	@RequestMapping("/auditTrainingCharge")
	@ResponseBody
	public int auditTrainingCharge(HttpServletRequest request,String fid,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		int i = trainingChargeService.auditTrainingCharge(fid,type,user.getFid());
		return i;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<TrainingCharge> getPageBean2(HttpServletRequest request,String companyId,String cfcar,String drivingName,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,");
		psql.append("t.cfdycs,t.cfbillstate from ct_ds_trainingcharge t  left join t_e_user u  on t.fcreatorid=u.fid ");
		psql.append("left join t_e_user us on t.fauditorid = us.fid left join ct_ds_trainingchargeentry tr on t.fid = tr.fparentid ");
		psql.append(" left join ct_ds_driving d on tr.cfjiaxiaoid = d.fid where t.fcontrolunitid = '"+companyId+"' ");
		if("".equals(cfcar)){
			
		}else{
			psql.append(" and tr.cfcar like '%"+cfcar+"%'");
		}
		if("".equals(drivingName)){
			
		}else{
			psql.append(" and d.fname_l2 like '%"+drivingName+"%'");
		}
		if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
		psql.append("order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
		int psize=100; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= trainingChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainingCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainingCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<TrainingCharge> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfdycs,t.cfbillstate from ct_ds_trainingcharge t  ");
		psql.append("left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '"+companyId+"' ");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		psql.append(" order by t.fbizdate desc");
		int psize=5; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= trainingChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainingCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainingCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=trainingChargeService.selectPageCount(psql);
		return paramMap;		
	}

	/**
	 * 导出Excel
	 *
	 * @param response
	 * @param request
	 * @param cfcar
	 * @param drivingName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping("/importTrainingCharge")
	public void importTrainingCharge(HttpServletResponse response, HttpServletRequest request,String cfcar,String drivingName,String beginTime,String endTime) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<TrainingChargeEntry> trainChargeEntrys = trainingChargeService.selTrainingChargeByCar(user.getFcompanyid(), cfcar.trim(), drivingName.trim(), beginTime, endTime);
		for (TrainingChargeEntry trainChargeEntry : trainChargeEntrys) {
			data.add(trainChargeEntry.getFnumber());
			data.add(trainChargeEntry.getFbizdate());
			data.add(trainChargeEntry.getFdescription());
			data.add(trainChargeEntry.getAuditName());
			data.add(trainChargeEntry.getCreateName());
			data.add(stateToString.billsState(trainChargeEntry.getCfbillstate()));
			data.add(trainChargeEntry.getCftime());
			data.add(trainChargeEntry.getCfprice());
			data.add(trainChargeEntry.getCfamount());
			data.add(trainChargeEntry.getCfnumber());
			data.add(trainChargeEntry.getCfremark());
			data.add(trainChargeEntry.getCfcar());
			data.add(trainChargeEntry.getCfcartype());
			data.add(trainChargeEntry.getDrivingName());
			data.add(trainChargeEntry.getCffandian());
			data.add(trainChargeEntry.getCfzsc());
			data.add(trainChargeEntry.getCfdycs());
		}
		//头部数据
		String head[] = {"单据编码", "业务日期", "备注", "审核人名称", "制单人名称", "单据状态", "时长", "单价", "金额", "人数", "备注","车牌", "车型","协议驾校", "返点",  "总时长", "打印次数"};
		//长度
		Integer length[] = {7000, 6000, 6500, 3000, 3000, 3000, 2600, 2600, 2600, 2000, 5600, 3000, 2600, 5000, 2600, 2600, 2600};

		List<Object> data2=listForSum(data,head,7,2);
		try {
			//导出Excel
			CommonExport.importExcelSum(response, "自带车训练收费" + TimeFormat.getNowTime2() + ".xls", "自带车训练收费", data, head, length,data2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 *统计方法
	 * @param list1 完成遍历的集合
	 * @param head  表头
	 * @param num   求和的第一个字段的下标
	 * @param sum  需要增加多少个字段
	 * @return
	 */
	public List<Object> listForSum(List<Object> list1,String[] head,int num,int sum){

		Double money=0.0;

		List<Object>list=new ArrayList<>();
		DecimalFormat df = new DecimalFormat("#.00");
		list.add("合计：");
		for (int i = 0; i < num - 1; i++) {
			list.add(" ");
		}
		for(int i=0;i<sum;i++){

			for (int j = 0; j < list1.size() / head.length; j++) {
				if (list1.get(num + head.length*j)==null || "".equals(list1.get(num + head.length * j))) {
					money += 0.00;
				} else {
					money += Double.parseDouble(list1.get(num + head.length * j) + "");
				}
			}
			if(money==0.00||money==null){
				list.add("0.00");
			}else{
				if(".00".equals(df.format(money))){
					list.add("");
				}else{
					list.add(df.format(money));
				}
			}
			num++;
			money = 0.00;
		}
		return list;
	}
}
